package logic

import (
	"context"
	"fmt"
	"shopping/model/mysql"
	"shopping/model/redis"
	"shopping/pkg"

	"shopping/shoppingrpc/internal/svc"
	"shopping/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *shoppingrpc.UserLoginRequest) (*shoppingrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Smslogin" + in.Phone)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("当前验证码错误")
	}
	var find mysql.User
	mysql.DB.Debug().Where("phone =?", in.Phone).Find(&find)
	if find.ID == 0 {
		return nil, fmt.Errorf("当前账号注册")
	}

	if find.Password != pkg.MdePassword(in.Password) {
		return nil, fmt.Errorf("当前密码错误")
	}
	redis.Client.Del("Smslogin" + in.Phone)
	return &shoppingrpc.UserLoginResponse{Id: int64(find.ID)}, nil
}
